package server

import (
	"context"
	"fmt"
	"gitee.com/dreamwood/ez"
	"net"
	"net/http"
	_ "net/http/pprof"
)

func Run() {
	ez.TriggerSync("BeforeServerRun", nil, context.TODO())
	handler := NewServerHandler()
	http.Handle("/static/", http.FileServer(http.Dir(ez.S.AssetDir)))
	http.Handle("/web/", http.FileServer(http.Dir(ez.S.AssetDir)))
	http.Handle("/", handler)
	ez.Debug(fmt.Sprintf("启动的运行端口为：%d", ez.S.Port))

	ch := make(chan int)
	l, e := net.Listen("tcp", fmt.Sprintf("%s:%d", ez.S.Host, ez.S.Port))
	if e != nil {
		ez.Debug("服务启动时发生错误")
		ez.PrintError(e)
	}
	go func() {
		defer func() { ch <- 1 }()
		e = http.Serve(l, nil)
		if e != nil {
			ez.Debug("服务启动时发生错误")
			ez.PrintError(e)
		}
	}()
	ez.S.Port = l.Addr().(*net.TCPAddr).Port
	ez.Debug(fmt.Sprintf("真实端口为：%d", ez.S.Port))
	ez.TriggerSync("AfterServerRun", nil, context.TODO())
	<-ch
}
